package wbbs.web.admin;

import cn.webwheel.Action;
import cn.webwheel.results.ErrorResult;
import cn.webwheel.results.TemplateResult;
import com.google.inject.Inject;
import wbbs.domain.Board;
import wbbs.service.BoardService;

import java.sql.SQLException;

public class board extends BaseAction {

    public Board board;

    public int boardCategoryId;

    @Inject
    BoardService boardService;

    @Action
    public Object html(int id) throws SQLException {

        ensureLoginPage();

        if (id == 0 && boardCategoryId != 0) {
            board = new Board();
            board.boardCategoryId = boardCategoryId;
            board.category = boardService.findCategory(boardCategoryId);
            if (board.category == null) {
                return new ErrorResult(404);
            }
        } else {
            board = boardService.findBoard(id);
            if (board == null) {
                return new ErrorResult(404);
            }
        }
        return new TemplateResult(this);
    }

    @Action
    public Object update() throws SQLException {

        ensureLoginAction();

        range(notNull(nospace(trim(board.name))), 1, 32);
        range(notNull(trim(board.remark)), 1, 512);

        if (board.id == 0) {
            notNull(boardService.findCategory(board.boardCategoryId));
            boardService.insertBoard(board);
        } else {
            boardService.updateBoard(board);
        }
        return ok().set("id", board.id);
    }
}
